package cn.tinlan.shopcoin.app.login;

import android.app.Activity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.CallBackProxy;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;

import org.json.JSONObject;

import butterknife.BindView;
import cn.tinlan.shopcoin.R;
import cn.tinlan.shopcoin.Utils.ToastUtils;
import cn.tinlan.shopcoin.Utils.VerificationCountDownTimer;
import cn.tinlan.shopcoin.base.BaseActivity;
import cn.tinlan.shopcoin.base.CustomApiResult;
import cn.tinlan.shopcoin.widget.category.Constants;

/**
 * Created by Mortimer on 2018/12/28. 10:50
 * 佛祖🙏，永无bug。
 */
public class forgetPasswordActivity extends BaseActivity implements View.OnClickListener{

    @BindView(R.id.forget_titleBar)
    TitleBar forget_titleBar;

    @BindView(R.id.forget_pwd_mobile)
    EditText fpwd_mobile;
    @BindView(R.id.fpwd_verify_et)
    EditText fpwd_verify_et;
    @BindView(R.id.fpwd_verify_tv)
    TextView fpwd_verify_tv;
    @BindView(R.id.forget_pwd_et)
    EditText forget_pwd_et;
    @BindView(R.id.forget_pwd_btn)
    Button forget_pwd_btn;

    private String mobile;

    private VerificationCountDownTimer verificationCountDownTimer;

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_forget_pwd;
    }

    @Override
    public void initView() {
        super.initView();
        drawableDefaultBar();

        initCountDownTimer();

        bindSubViewsClickEvents();
    }

    private void bindSubViewsClickEvents() {

        forget_titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) {
                finish();
            }

            @Override
            public void onTitleClick(View v) {

            }

            @Override
            public void onRightClick(View v) {

            }
        });
        fpwd_verify_tv.setOnClickListener(this);
        forget_pwd_btn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.fpwd_verify_tv:
                getVerify();
                break;
            case R.id.forget_pwd_btn:
                resetting();
                break;
        }
    }

    private void resetting() {

        String mobile = fpwd_mobile.getText().toString().trim();

        if (mobile.isEmpty() || mobile.length() != 11) {
            ToastUtils.show("请输入正确的手机号");
            return;
        }
        String verify = fpwd_verify_et.getText().toString().trim();
        String pwd    = forget_pwd_et.getText().toString().trim();
        if (verify.isEmpty()) {
            ToastUtils.show("请输入验证码");
            return;
        }

        if (pwd.length() < 6) {
            ToastUtils.show("请输入至少6位的密码");
            return;
        }


        EasyHttp.post(Constants.PWDRestting)
                .params("mobile",mobile)
                .params("verify",verify)
                .params("pwd",pwd)
                .execute(new CallBackProxy<CustomApiResult<String>, String>(new SimpleCallBack<String>() {
                    @Override
                    public void onError(ApiException e) {
                        ToastUtils.show("获取失败");
                    }
                    @Override
                    public void onSuccess(String s) {
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            if (jsonObject.getString("code").equals("2")){
                                ToastUtils.show(jsonObject.getString("data"));
                            }else if(jsonObject.getString("code").equals("1")){
                                ToastUtils.show(jsonObject.getString("data"));
                            }else {
                                ToastUtils.show("网络异常");
                            }
                        }catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }) {
                });
    }


    private void getVerify() {


        String mobile = fpwd_mobile.getText().toString().trim();

        if (mobile.isEmpty() || mobile.length() != 11) {
            ToastUtils.show("请输入正确的手机号");
            return;
        }
        verificationCountDownTimer.timerStart(true);

        EasyHttp.post(Constants.ForgetPWDVerify)
                .params("mobile",mobile)
                .execute(new CallBackProxy<CustomApiResult<String>, String>(new SimpleCallBack<String>() {
                    @Override
                    public void onError(ApiException e) {
                        ToastUtils.show("获取失败");
                    }
                    @Override
                    public void onSuccess(String s) {
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            if (jsonObject.getString("code").equals("2")){
                                ToastUtils.show(jsonObject.getString("data"));
                            }
                        }catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }) {
                });
    }

    private void initCountDownTimer() {

        if (!VerificationCountDownTimer.FLAG_FIRST_IN &&
                VerificationCountDownTimer.curMillis+60000>System.currentTimeMillis()){
            setCountDownTimer(VerificationCountDownTimer.curMillis+60000-System.currentTimeMillis());
//            Log.d("yanzhengma","yanzhengma>>>>>>>>");
            verificationCountDownTimer.timerStart(false);
        }else {
//          /  Log.d("yanzhengma","yanzhengma");
            setCountDownTimer(60000);
        }
    }

    private void setCountDownTimer(final long countDownTimer) {
        verificationCountDownTimer = new VerificationCountDownTimer(countDownTimer,1000) {


            @Override
            public void onTick(long millisUntilFinished) {
                super.onTick(millisUntilFinished);
                fpwd_verify_tv.setEnabled(false);
                fpwd_verify_tv.setText((millisUntilFinished/1000)+"s");
            }

            @Override
            public void onFinish() {
                super.onFinish();
                fpwd_verify_tv.setEnabled(true);
                fpwd_verify_tv.setText("重新获取");
                if (countDownTimer != 60000) {
                    setCountDownTimer(60000);
                }
            }
        };
    }

    //实现点击屏幕收起键盘
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if(ev.getAction()==MotionEvent.ACTION_DOWN){
            View v=getCurrentFocus();
            boolean  hideInputResult =isShouldHideInput(v,ev);
            Log.v("hideInputResult","zzz-->>"+hideInputResult);
            if(hideInputResult){
                v.clearFocus();
                InputMethodManager imm = (InputMethodManager) forgetPasswordActivity.this
                        .getSystemService(Activity.INPUT_METHOD_SERVICE);
                if(v != null){
                    if(imm.isActive()){
                        imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    }
                }
            }
        }
        return super.dispatchTouchEvent(ev);
    }
    public  boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = { 0, 0 };
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            //之前一直不成功的原因是,getX获取的是相对父视图的坐标,getRawX获取的才是相对屏幕原点的坐标！！！
//            Log.v("leftTop[]","zz--left:"+left+"--top:"+top+"--bottom:"+bottom+"--right:"+right);
//            Log.v("event","zz--getX():"+event.getRawX()+"--getY():"+event.getRawY());
            if (event.getRawX() > left && event.getRawX() < right
                    && event.getRawY() > top && event.getRawY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }
}
